﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
//using Microsoft.SqlServer.Management.Smo;
using System.Configuration;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography;

namespace Punia
{

    public partial class mainForm : Form
    {
        bool loggedIn = false;

        const string ServersElement = "myServers";
        const string Server = "oneServer";
        public const string sep = "@#$%^&!*";

        const string AppName = "Service broken...";
        const string AppDesc = "Application for SQL Server Service Broker diagnostics ";

        const string windows_authentication = "windows authentication";
        const string sql_server_authentication = "sql server authentication";
        const string connection_string_sql = "Data Source={0};Initial Catalog=master; User Id={1}; Password={2};";
        const string connection_string_windows = "Data Source={0};Initial Catalog=master; Integrated Security=SSPI;";

        public const string tempPath = "C:\\ServiceBrokenTemp";

        string current_database = "";

        public string Database
        {
            get
            {
                return current_database;
            }
        }

        string current_service_broker_guid = "";

        int interval = 0;

        Timer timer = new Timer();

        SqlConnection connection = new SqlConnection();

        public SqlConnection Connection
        {
            get
            {
                return connection;
            }
        }

        private void TempPath()
        {
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            else
            {
                string[] files = Directory.GetFiles(tempPath, "*.*");

                foreach (string file in files)
                {
                    File.Delete(file);
                }
            }
        }

        
        public mainForm()
        {
            InitializeComponent();

            //TempPath();

            //this.WindowState = FormWindowState.Maximized;

            //cbLoginType.SelectedIndex = 0;

            //getServers();

            //timer.Tick += new EventHandler(timer_Tick); ;
        }

        private void getServers()
        {
            scMain.Panel1Collapsed = false;
            scMain.Panel2Collapsed = false;

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            XmlNodeList element = doc.GetElementsByTagName(ServersElement);

            cbServer.Items.Clear();

            if (element[0] != null)
            {
                foreach (XmlNode item in element[0].ChildNodes)
                {
                    cbServer.Items.Add(item.Attributes[0].Value.ToString());
                }
            }

        }

        private bool ValidLogin
        {
            get
            {
                if (cbServer.Text == string.Empty)
                {
                    return false;
                }

                if (((string)cbLoginType.SelectedItem).ToLower() == windows_authentication)
                {
                    return true;
                }

                if (tbPassword.Text != string.Empty && tbUser.Text != string.Empty)
                {
                    return true;
                }

                return false;
            }
        }

        private void UpdateConfigData()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            XmlNodeList element = doc.GetElementsByTagName("connectionStrings");

            bool found = false;

            foreach (XmlNode node in element[0].ChildNodes)
            {
                if (node.Name == "add")
                {
                    foreach (XmlAttribute attrib in node.Attributes)
                    {
                        if (attrib.Name == "name" && attrib.Value == "SQLServer")
                        {
                            found = true;
                        }

                        if (found && attrib.Name == "connectionString")
                        {
                            if (((string)cbLoginType.SelectedItem).ToLower() == windows_authentication)
                            {
                                attrib.Value = string.Format(connection_string_windows, (string)cbServer.SelectedItem);
                            }
                            else
                            {
                                attrib.Value = string.Format(connection_string_sql, (string)cbServer.SelectedItem, tbUser.Text, tbPassword.Text);
                            }
                        }
                    }
                }
            }

            doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

        private void RegisterServers()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            bool found = false;

            XmlNodeList element = doc.GetElementsByTagName(ServersElement);

            if (element[0] != null)
            {
                if (element[0].ChildNodes.Count > 0)
                {
                    foreach (XmlNode item in element[0].ChildNodes)
                    {
                        foreach (XmlAttribute atr in item.Attributes)
                        {
                            if (atr.Value == cbServer.Text)
                            {
                                found = true;

                                if (found)
                                {
                                    if (atr.Name == "login")
                                    {
                                        atr.Value = tbUser.Text;
                                    }

                                    if (atr.Name == "authentication")
                                    {
                                        atr.Value = cbLoginType.Text;
                                    }
                                }
                            }
                        }

                        if (found)
                        {
                            break;
                        }
                    }

                    if (!found)
                    {
                        XmlNode n = doc.CreateNode(XmlNodeType.Element, Server, null);

                        XmlAttribute a = doc.CreateAttribute("name");
                        a.Value = cbServer.Text;

                        n.Attributes.Append(a);

                        a = doc.CreateAttribute("login");
                        a.Value = tbUser.Text;

                        n.Attributes.Append(a);

                        a = doc.CreateAttribute("authentication");
                        a.Value = cbLoginType.Text;

                        n.Attributes.Append(a);

                        element[0].AppendChild(n);
                    }
                }
                else
                {
                    XmlNode n = doc.CreateNode(XmlNodeType.Element, Server, null);

                    XmlAttribute a = doc.CreateAttribute("name");
                    a.Value = cbServer.Text;

                    n.Attributes.Append(a);

                    a = doc.CreateAttribute("login");
                    a.Value = tbUser.Text;

                    n.Attributes.Append(a);

                    a = doc.CreateAttribute("authentication");
                    a.Value = cbLoginType.Text;

                    n.Attributes.Append(a);

                    element[0].AppendChild(n);
                }
            }
            else
            {
                if (element[0] != null)
                {
                    if (element[0].ChildNodes.Count > 0)
                    {
                        XmlNode n = doc.CreateNode(XmlNodeType.Element, ServersElement, null);

                        XmlNode s = doc.CreateNode(XmlNodeType.Element, Server, null);

                        XmlAttribute a = doc.CreateAttribute("name");
                        a.Value = cbServer.Text;

                        s.Attributes.Append(a);

                        a = doc.CreateAttribute("login");
                        a.Value = tbUser.Text;

                        s.Attributes.Append(a);

                        a = doc.CreateAttribute("authentication");
                        a.Value = cbLoginType.Text;

                        s.Attributes.Append(a);

                        n.AppendChild(s);

                        element[0].AppendChild(n);
                    }
                }
            }

            doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

        private void OpenConnection()
        {
            getServers();

            string connectionString;

            if (((string)cbLoginType.SelectedItem).ToLower() == windows_authentication)
            {
                connectionString = string.Format(connection_string_windows, (string)cbServer.Text);
            }
            else
            {
                connectionString = string.Format(connection_string_sql, (string)cbServer.Text, tbUser.Text, tbPassword.Text);
            }

            connection.ConnectionString = connectionString;
            connection.Open();

            RegisterServers();
        }

        private void showMenu()
        {
            utilitiesToolStripMenuItem.Visible = true;
            cleaningToolStripMenuItem.Visible = true;
            conversationToolStripMenuItem.Visible = true;
            alteringToolStripMenuItem.Visible = true;
            refreshToolStripMenuItem.Visible = true;

            btnHide.Visible = true;
        }
        
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (!ValidLogin)
            {
                MessageBox.Show("Invalid login");

                return;
            }

            try
            {
                OpenConnection();

                scMain.Panel1Collapsed = true;

                tcMain.Visible = true;

                tcMain.TabPages["tabBrokers"].Focus();

                ShowTabs();

                if (dgvBrokers.Rows.Count > 0)
                {
                    current_database = dgvBrokers.Rows[0].Cells[0].Value.ToString();
                    current_service_broker_guid = dgvBrokers.Rows[0].Cells[1].Value.ToString();

                    showMenu();

                    this.Text = AppName + " [" + current_database + "]";
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            scMain.Panel1Collapsed = false;

            //tcMain.Visible = false;

            //utilitiesToolStripMenuItem.Visible = false;
            //cleaningToolStripMenuItem.Visible = false;
            //conversationToolStripMenuItem.Visible = false;
            //alteringToolStripMenuItem.Visible = false;
            //refreshToolStripMenuItem.Visible = false;
            //connection.Close();

            //this.Text = AppName;
        }

        private void ShowTabs()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("SELECT   name AS [Database Name],");
                sb.AppendLine("         Upper(service_broker_guid) AS GUID,");
                sb.AppendLine("         is_broker_enabled [Is broker enabled?]");
                sb.AppendLine("FROM sys.databases");
                //sb.AppendLine("WHERE is_broker_enabled = 1");

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvBrokers.DataSource = ds.Tables[0];
                dgvBrokers.Columns["Is broker enabled?"].ReadOnly = false;

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void mainForm_Move(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                niServiceBroken.ShowBalloonTip(300, AppName, AppDesc, ToolTipIcon.Info);
            }
        }

        private void cbLoginType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbLoginType.SelectedItem.ToString().ToLower())
            {
                case windows_authentication:
                    lblPassword.Enabled = false;
                    tbPassword.Enabled = false;
                    tbPassword.Text = "";

                    lblUser.Enabled = false;
                    tbUser.Enabled = false;
                    tbUser.Text = "";
                    break;
                case sql_server_authentication:
                    lblPassword.Enabled = true;
                    tbPassword.Enabled = true;

                    lblUser.Enabled = true;
                    tbUser.Enabled = true;
                    break;
                default:
                    break;
            }
        }

        private void dgvBrokers_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvBrokers.CurrentRow != null)
            {
                current_database = dgvBrokers.Rows[e.RowIndex].Cells[0].Value.ToString();
                current_service_broker_guid = dgvBrokers.Rows[e.RowIndex].Cells[1].Value.ToString();

                this.Text = AppName + " [" + current_database + "]";
            }
        }

        private void tcMain_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabTransmission_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   transmission_status [Transmission status],");
                sb.AppendLine("         from_service_name [From service],");
                sb.AppendLine("         to_service_name [To service],");
                sb.AppendLine("         to_broker_instance [To broker instance],");
                sb.AppendLine("         cast(message_body as xml) [Message body], ");
                sb.AppendLine("         service_contract_name [Contract name],");
                sb.AppendLine("         enqueue_time [Enqueue time], ");
                sb.AppendLine("         message_sequence_number [Message sequence number],");
                sb.AppendLine("         case is_conversation_error when 1 then 'Yes' else NULL end [Conversation error?], ");
                sb.AppendLine("         case is_end_of_dialog when 1 then 'Yes' else NULL end [End of dialog?],");
                sb.AppendLine("         Upper(conversation_handle) [Conversation handle]");
                sb.AppendLine("FROM sys.transmission_queue;");

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvTransmission.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                try
                {
                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine("USE [" + current_database + "];");
                    sb.AppendLine("SELECT   transmission_status [Transmission status],");
                    sb.AppendLine("         from_service_name [From service],");
                    sb.AppendLine("         to_service_name [To service],");
                    sb.AppendLine("         to_broker_instance [To broker instance],");
                    sb.AppendLine("         cast(message_body as nvarchar(max)) [Message body], ");
                    sb.AppendLine("         service_contract_name [Contract name],");
                    sb.AppendLine("         enqueue_time [Enqueue time], ");
                    sb.AppendLine("         message_sequence_number [Message sequence number],");
                    sb.AppendLine("         case is_conversation_error when 1 then 'Yes' else NULL end [Conversation error?], ");
                    sb.AppendLine("         case is_end_of_dialog when 1 then 'Yes' else NULL end [End of dialog?],");
                    sb.AppendLine("         Upper(conversation_handle) [Conversation handle]");
                    sb.AppendLine("FROM sys.transmission_queue;");

                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand();
                    da.SelectCommand.CommandText = sb.ToString();
                    da.SelectCommand.CommandTimeout = 0;
                    da.SelectCommand.CommandType = CommandType.Text;
                    da.SelectCommand.Connection = connection;

                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    dgvTransmission.DataSource = ds.Tables[0];
                }
                catch (Exception new_exception)
                {
                    MessageBox.Show(new_exception.Message);
                }
            }
        }

        private void dgvConnections_Enter(object sender, EventArgs e)
        {
        }

        private void tabConnections_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   state_desc [State],");
                sb.AppendLine("         connect_time [Connect time],");
                sb.AppendLine("         login_time [Login time],");
                sb.AppendLine("         authentication_method [Authentication method],");
                sb.AppendLine("         principal_name [Principal name], ");
                sb.AppendLine("         remote_user_name [Remote user name], ");
                sb.AppendLine("         last_activity_time [Last activity time], ");
                sb.AppendLine("         case is_accept when 1 then 'Yes' else null end [Is accept?], ");
                sb.AppendLine("         login_state_desc [Login state], ");
                sb.AppendLine("         encryption_algorithm_desc [Encryption algorithm], ");
                sb.AppendLine("         receives_posted [Receives posted], ");
                sb.AppendLine("         case is_receive_flow_controlled when 1 then 'Yes' else null end [Is receive flow controlled?], ");
                sb.AppendLine("         sends_posted [Sends posted], ");
                sb.AppendLine("         case is_send_flow_controlled when 1 then 'Yes' else null end [Is send flow controlled?], ");
                sb.AppendLine("         total_sends [Total sends], ");
                sb.AppendLine("         total_receives [Total receives] ");
                sb.AppendLine("FROM sys.dm_broker_connections");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvConnections.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabEndpoints_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   e.name [Name], ");
                sb.AppendLine("         sp.name [Principal], ");
                sb.AppendLine("         e.protocol_desc [Protocol], ");
                sb.AppendLine("         e.type_desc [Type], ");
                sb.AppendLine("         e.state_desc [State], ");
                sb.AppendLine("         te.Port, ");
                sb.AppendLine("         case when te.ip_Address is null then 'All' else te.ip_address end as [Listener IP], ");
                sb.AppendLine("         case e.is_admin_endpoint when 1 then 'Yes' else null end [Is admin endpoint?], ");
                sb.AppendLine("         case e.is_message_forwarding_enabled when 1 then 'Yes' else null end [Is message forwarding enabled?], ");
                sb.AppendLine("         e.message_forwarding_size [Message forwarding size], ");
                sb.AppendLine("         e.connection_auth_desc [Connection authentication description], ");
                sb.AppendLine("         c.name [Certificate], ");
                sb.AppendLine("         e.encryption_algorithm_desc [Encryption algorithm description] ");
                sb.AppendLine("FROM sys.service_broker_endpoints e ");
                sb.AppendLine("LEFT JOIN sys.tcp_endpoints te ON e.endpoint_id = te.endpoint_id");
                sb.AppendLine("LEFT JOIN master.sys.certificates c on e.certificate_id = c.certificate_id");
                sb.AppendLine("OUTER APPLY sys.server_principals sp ");
                sb.AppendLine("WHERE e.principal_id = sp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvEndpoints.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabQueueMonitors_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   qm.state [State], ");
                sb.AppendLine("         qm.last_empty_rowset_time [Last empty rowset time], ");
                sb.AppendLine("         qm.last_activated_time [Last activated time], ");
                sb.AppendLine("         qm.tasks_waiting [Tasks waiting], ");
                sb.AppendLine("         db.name [Database], ");
                sb.AppendLine("         sq.name [Queue] ");
                sb.AppendLine("FROM sys.dm_broker_queue_monitors qm ");
                sb.AppendLine("INNER JOIN sys.databases db ON qm.database_id = db.database_id");
                sb.AppendLine("LEFT JOIN sys.service_queues sq ON qm.queue_id = sq.object_id");
                sb.AppendLine("WHERE qm.database_id = db_id()");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvQueueMonitors.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabActivatedTasks_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   at.procedure_name [Procedure],");
                sb.AppendLine("         at.execute_as [Execute as...], ");
                sb.AppendLine("         db.name [Database], ");
                sb.AppendLine("         sq.name [Queue], ");
                sb.AppendLine("         at.spid [SPID] ");
                sb.AppendLine("FROM sys.dm_broker_activated_tasks at ");
                sb.AppendLine("INNER JOIN sys.databases db ON at.database_id = db.database_id");
                sb.AppendLine("LEFT JOIN sys.service_queues sq ON at.queue_id = sq.object_id");
                sb.AppendLine("WHERE at.database_id = db_id()");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvActivatedTasks.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabRoutes_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   r.name [Route name],");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         r.remote_service_name [Remote service name], ");
                sb.AppendLine("         r.broker_instance [Broker instance], ");
                sb.AppendLine("         r.lifetime [Lifetime], ");
                sb.AppendLine("         r.address [Addres], ");
                sb.AppendLine("         r.mirror_address [Mirror address] ");
                sb.AppendLine("FROM sys.routes r ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on r.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvRoutes.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabInfrastructure_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   s.name [Service name],");
                sb.AppendLine("         s.service_id ");
                sb.AppendLine("FROM sys.services s ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on s.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvInfServices.DataSource = ds.Tables[0];
                dgvInfServices.Columns["service_id"].Visible = false;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
        
        private void InfrastructureQueues(object service_id)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   sq.name [Queue name],");
                sb.AppendLine("         sq.type_desc [Description], ");
                sb.AppendLine("         sq.max_readers [Max readers], ");
                sb.AppendLine("         sq.activation_procedure [Activation procedure], ");
                sb.AppendLine("         dp.name [Execute as principal], ");
                sb.AppendLine("         case sq.is_activation_enabled when 1 then 'Yes' else null end as [Is activation enabled?],");
                sb.AppendLine("         case sq.is_receive_enabled when 1 then 'Yes' else null end as [Is receive enabled?],");
                sb.AppendLine("         case sq.is_enqueue_enabled when 1 then 'Yes' else null end as [Is enqueue enabled?],");
                sb.AppendLine("         case sq.is_retention_enabled when 1 then 'Yes' else null end as [Is retention enabled?]");
                sb.AppendLine("FROM sys.service_queue_usages squ ");
                sb.AppendLine("INNER JOIN sys.service_queues sq ON squ.service_queue_id = sq.object_id ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on sq.execute_as_principal_id = dp.principal_id");
                sb.AppendLine("WHERE squ.service_id = " + service_id.ToString());
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvInfQueues.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void InfrastructureContracts(object service_id)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   sc.name [Contract name],");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         sc.service_contract_id");
                sb.AppendLine("FROM sys.service_contract_usages scu ");
                sb.AppendLine("INNER JOIN sys.service_contracts sc ON scu.service_contract_id = sc.service_contract_id ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on sc.principal_id = dp.principal_id");
                sb.AppendLine("WHERE scu.service_id = " + service_id.ToString());
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvInfContracts.DataSource = ds.Tables[0];
                dgvInfContracts.Columns["service_contract_id"].Visible = false;

                if (dgvInfContracts.Rows.Count == 0)
                {
                    InfrastructureMessageTypes(0);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
        
        private void dgvInfServices_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            object service_id = dgvInfServices.Rows[e.RowIndex].Cells["service_id"].Value;

            InfrastructureQueues(service_id);
            InfrastructureContracts(service_id);
        }

        private void dgvInfQueues_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
        }

        
        private void InfrastructureMessageTypes(object service_contract_id)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   smt.name [Message type name],");
                sb.AppendLine("         case scmu.is_sent_by_initiator when 1 then 'Yes' else null end [Is sent by initiator?], ");
                sb.AppendLine("         case scmu.is_sent_by_target when 1 then 'Yes' else null end [Is sent by target?], ");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         smt.validation_desc [Validation],");
                sb.AppendLine("         smt.xml_collection_id,");
                sb.AppendLine("         (select name from sys.xml_schema_collections WHERE xml_collection_id = smt.xml_collection_id) [XML schema collection]");
                sb.AppendLine("FROM sys.service_contract_message_usages scmu ");
                sb.AppendLine("INNER JOIN sys.service_message_types smt ON scmu.message_type_id = smt.message_type_id ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on smt.principal_id = dp.principal_id");
                sb.AppendLine("WHERE scmu.service_contract_id = " + service_contract_id.ToString());
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvInfMessages.DataSource = ds.Tables[0];
                dgvInfMessages.Columns["xml_collection_id"].Visible = false;

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        
        private void dgvInfContracts_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            object service_contract_id = dgvInfContracts.Rows[e.RowIndex].Cells["service_contract_id"].Value;

            InfrastructureMessageTypes(service_contract_id);
        }

        private string XmlSchemaCollection(object principal, object schema_collection)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("declare @schema_owner sysname;");
                sb.AppendLine("select @schema_owner = s.name ");
                sb.AppendLine("from sys.xml_schema_collections x ");
                sb.AppendLine("inner join sys.schemas s on x.schema_id = s.schema_id ");
                sb.AppendLine("where x.name = @SchemaName;");
                sb.AppendLine("select xml_schema_namespace(@schema_owner,@SchemaName) as text;");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Parameters.AddWithValue("@dbo", principal);
                da.SelectCommand.Parameters.AddWithValue("@SchemaName", schema_collection);
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    return ds.Tables[0].Rows[0].ItemArray[0].ToString();
                }

                return string.Empty;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

            return string.Empty;
        }

        private void dgvInfMessages_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
        }

        private object schema_principal;
        private object schema_collection;
        private string xmlSchema;

        private void dgvInfMessages_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void showXMLSchemaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (xmlSchema != string.Empty)
            {
                string fileName = tempPath + Path.GetRandomFileName() + ".xml";
                StreamWriter sw = File.CreateText(fileName);
                sw.Write(xmlSchema);
                sw.Close();

                XmlBrowser xb = new XmlBrowser();
                xb.browser.Navigate(fileName);
                xb.Show();

                xmlSchema = string.Empty;
            }
        }

        string intrastructureColumnName;

        private void dgvInfMessages_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (intrastructureColumnName == "XML schema collection") cmsXml.Show(Control.MousePosition);
            }
        }

        private void dgvInfMessages_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex > 0)
            {
                intrastructureColumnName = dgvInfMessages.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;

                if (dgvInfMessages.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name == "XML schema collection")
                {
                    schema_principal = dgvInfMessages.Rows[e.RowIndex].Cells["principal"].Value;
                    schema_collection = dgvInfMessages.Rows[e.RowIndex].Cells["XML schema collection"].Value;

                    if (schema_collection.ToString() != string.Empty) xmlSchema = XmlSchemaCollection(schema_principal, schema_collection);
                }
            }
        }

        private void tabQueues_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   s.name [Queue name],");
                sb.AppendLine("         s.object_id, ");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         sch.name [Schema], ");
                sb.AppendLine("         case s.is_ms_shipped when 1 then 'Yes' else null end [Is MS shipped?], ");
                sb.AppendLine("         case s.is_published when 1 then 'Yes' else null end [Is published?], ");
                sb.AppendLine("         s.max_readers [Max readers], ");
                sb.AppendLine("         s.activation_procedure [Activation procedure], ");
                sb.AppendLine("         dpe.name [Execute as principal], ");
                sb.AppendLine("         case s.is_activation_enabled when 1 then 'Yes' else null end [Is activation enabled?], ");
                sb.AppendLine("         case s.is_receive_enabled when 1 then 'Yes' else null end [Is receive enabled?], ");
                sb.AppendLine("         case s.is_enqueue_enabled when 1 then 'Yes' else null end [Is enqueue enabeld?], ");
                sb.AppendLine("         case s.is_retention_enabled when 1 then 'Yes' else null end [Is retention enabled] ");
                sb.AppendLine("FROM sys.service_queues s ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on s.principal_id = dp.principal_id");
                sb.AppendLine("LEFT JOIN sys.database_principals dpe on s.execute_as_principal_id = dpe.principal_id");
                sb.AppendLine("INNER JOIN sys.schemas sch on s.schema_id = sch.schema_id ");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvServiceQueues.DataSource = ds.Tables[0];
                dgvServiceQueues.Columns["object_id"].Visible = false;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void dgvServiceQueues_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string queue_name = dgvServiceQueues.Rows[e.RowIndex].Cells["Queue name"].Value.ToString();
                string schema = dgvServiceQueues.Rows[e.RowIndex].Cells["Schema"].Value.ToString();

                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   case Status when 0 then 'Ready' when 1 then 'Received' when 2 then 'Not yet complete' when 3 then 'Retained sent message' else '???' end [Status],");
                sb.AppendLine("         Priority, ");
                sb.AppendLine("         queuing_order [Queuing order], ");
                sb.AppendLine("         upper(conversation_group_id) [Conversation group ID], ");
                sb.AppendLine("         message_sequence_number [Message sequence number], ");
                sb.AppendLine("         service_name [Service name], ");
                sb.AppendLine("         service_contract_name [Service contract name], ");
                sb.AppendLine("         message_type_name [Message type name], ");
                sb.AppendLine("         validation [Validation], ");
                sb.AppendLine("         case when validation = 'X' then cast(message_body as xml) else cast(message_body as nvarchar(max)) end [Message body] ");
                sb.AppendLine("FROM [" + schema + "].[" + queue_name + "]");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvServiceQueuesContent.DataSource = ds.Tables[0];
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void dgvServiceQueuesContent_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (validation == "X")
            {
                if (e.Button == MouseButtons.Right)
                {
                    cmsXml.Show(Control.MousePosition);
                }
            }
        }

        string validation;
        string messageColumn;

        string message_body;

        private void dgvServiceQueuesContent_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0)
            {
                validation = dgvServiceQueuesContent.Rows[e.RowIndex].Cells["Validation"].Value.ToString();
                messageColumn = dgvServiceQueuesContent.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;
                message_body = dgvServiceQueuesContent.Rows[e.RowIndex].Cells["Message body"].Value.ToString();

                if (validation == "X")
                {
                    xmlSchema = message_body;
                }
            }
        }

        private void tabConverstions_Enter(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            DataSet ds;

            try
            {
                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   upper(ce.conversation_handle) [Conversation handle],");
                sb.AppendLine("         upper(ce.conversation_id) [Conversation ID], ");
                sb.AppendLine("         case ce.is_initiator when 1 then 'Yes' else null end [Is initiator?], ");
                sb.AppendLine("         ss.name [Service], ");
                sb.AppendLine("         ce.Lifetime, ");
                sb.AppendLine("         ce.state_desc [State], ");
                sb.AppendLine("         ce.far_service [Far service], ");
                sb.AppendLine("         upper(ce.far_broker_instance) [Far broker instance], ");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         ce.far_principal_id [Far principal ID], ");
                sb.AppendLine("         upper(ce.outbound_session_key_identifier) [Outbound session key identifier], ");
                sb.AppendLine("         upper(ce.inbound_session_key_identifier) [Inbound session key identifier], ");
                sb.AppendLine("         ce.security_timestamp [Security timestamp], ");
                sb.AppendLine("         ce.dialog_timer [Dialog timer], ");
                sb.AppendLine("         ce.send_sequence [Next send sequence number], ");
                sb.AppendLine("         ce.end_dialog_sequence [Sequence number of EndDialog message], ");
                sb.AppendLine("         ce.receive_sequence [Next message number expected in receive sequence], ");
                sb.AppendLine("         ce.receive_sequence_frag [Next message fragment number expected in receive sequence], ");
                sb.AppendLine("         ce.system_sequence [The sequence number of last system message for this dialog], ");
                sb.AppendLine("         ce.first_out_of_order_sequence [The sequence number of first message in out-of-order messages for this cnversation], ");
                sb.AppendLine("         ce.last_out_of_order_sequence [The sequence number of last message in out-of-order messages for this cnversation], ");
                sb.AppendLine("         ce.last_out_of_order_frag [The sequence number of last message in out-of-order fragments for this cnversation], ");
                sb.AppendLine("         case ce.is_system when 1 then 'Yes' else null end [Is system?], ");
                sb.AppendLine("         ce.Priority ");
                sb.AppendLine("FROM sys.conversation_endpoints ce ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on ce.principal_id = dp.principal_id");
                sb.AppendLine("left join sys.services ss on ce.service_id = ss.service_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                ds = new DataSet();
                da.Fill(ds);

                dgvConversations.DataSource = ds.Tables[0];
            }
            catch
            {
                try
                {
                    sb = new StringBuilder();

                    sb.AppendLine("USE [" + current_database + "];");
                    sb.AppendLine("SELECT   upper(ce.conversation_handle) [Conversation handle],");
                    sb.AppendLine("         upper(ce.conversation_id) [Conversation ID], ");
                    sb.AppendLine("         case ce.is_initiator when 1 then 'Yes' else null end [Is initiator?], ");
                    sb.AppendLine("         ss.name [Service], ");
                    sb.AppendLine("         ce.Lifetime, ");
                    sb.AppendLine("         ce.state_desc [State], ");
                    sb.AppendLine("         ce.far_service [Far service], ");
                    sb.AppendLine("         upper(ce.far_broker_instance) [Far broker instance], ");
                    sb.AppendLine("         dp.name [Principal], ");
                    sb.AppendLine("         ce.far_principal_id [Far principal ID], ");
                    sb.AppendLine("         upper(ce.outbound_session_key_identifier) [Outbound session key identifier], ");
                    sb.AppendLine("         upper(ce.inbound_session_key_identifier) [Inbound session key identifier], ");
                    sb.AppendLine("         ce.security_timestamp [Security timestamp], ");
                    sb.AppendLine("         ce.dialog_timer [Dialog timer], ");
                    sb.AppendLine("         ce.send_sequence [Next send sequence number], ");
                    sb.AppendLine("         ce.end_dialog_sequence [Sequence number of EndDialog message], ");
                    sb.AppendLine("         ce.receive_sequence [Next message number expected in receive sequence], ");
                    sb.AppendLine("         ce.receive_sequence_frag [Next message fragment number expected in receive sequence], ");
                    sb.AppendLine("         ce.system_sequence [The sequence number of last system message for this dialog], ");
                    sb.AppendLine("         ce.first_out_of_order_sequence [The sequence number of first message in out-of-order messages for this cnversation], ");
                    sb.AppendLine("         ce.last_out_of_order_sequence [The sequence number of last message in out-of-order messages for this cnversation], ");
                    sb.AppendLine("         ce.last_out_of_order_frag [The sequence number of last message in out-of-order fragments for this cnversation], ");
                    sb.AppendLine("         case ce.is_system when 1 then 'Yes' else null end [Is system?] ");
                    sb.AppendLine("FROM sys.conversation_endpoints ce ");
                    sb.AppendLine("LEFT JOIN sys.database_principals dp on ce.principal_id = dp.principal_id");
                    sb.AppendLine("left join sys.services ss on ce.service_id = ss.service_id");
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand();
                    da.SelectCommand.CommandText = sb.ToString();
                    da.SelectCommand.CommandTimeout = 0;
                    da.SelectCommand.CommandType = CommandType.Text;
                    da.SelectCommand.Connection = connection;

                    ds = new DataSet();
                    da.Fill(ds);

                    dgvConversations.DataSource = ds.Tables[0];
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }


        }

        private void tabCertificates_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   ce.name [Name], ");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         ce.pvt_key_encryption_type_desc [Private key encryption type description], ");
                sb.AppendLine("         case ce.is_active_for_begin_dialog when 1 then 'Yes' else null end [Is active for begin dialog?], ");
                sb.AppendLine("         ce.issuer_name [Issuer name], ");
                sb.AppendLine("         Upper(ce.cert_serial_number) [Cert serial number], ");
                sb.AppendLine("         ce.string_sid [String SID], ");
                sb.AppendLine("         ce.subject [Subject of this certificate], ");
                sb.AppendLine("         ce.expiry_date [When certificate expires], ");
                sb.AppendLine("         ce.start_date [When certificate becomes valid], ");
                sb.AppendLine("         ce.attested_by [Attested by] ");
                sb.AppendLine("FROM sys.certificates ce ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on ce.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvCertificates.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabForwarded_Enter(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            DataSet ds;

            try
            {
                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   upper(conversation_id) [Conversation ID], ");
                sb.AppendLine("         case is_initiator when 1 then 'Yes' else null end [Is initiator?], ");
                sb.AppendLine("         to_service_name [Name of the service to which this message is sent], ");
                sb.AppendLine("         to_broker_instance [Identifier of the broker that hosts the service to which this message is sent],");
                sb.AppendLine("         from_service_name [Name of the service that this message is from], ");
                sb.AppendLine("         from_broker_instance [Identifier of the broker that hosts the service that this message is from], ");
                sb.AppendLine("         adjacent_broker_address [Network address to which this message is being sent], ");
                sb.AppendLine("         message_sequence_number [Sequence number of the message], ");
                sb.AppendLine("         message_fragment_number [Fragment number that this transport message contains], ");
                sb.AppendLine("         hops_remaining [Number of times the message may be retransmitted before reaching the final destination], ");
                sb.AppendLine("         time_to_live [Maximum time for the message to remain active], ");
                sb.AppendLine("         time_consumed [Time that the message has already been active], ");
                sb.AppendLine("         Upper(message_id) [ID of the message], ");
                sb.AppendLine("         pvt_key_last_backup_date [When certificate’s private key was last exported] ");
                sb.AppendLine("FROM sys.dm_broker_forwarded_messages ");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                ds = new DataSet();
                da.Fill(ds);
            }
            catch
            {

                try
                {
                    sb = new StringBuilder();

                    sb.AppendLine("USE [" + current_database + "];");
                    sb.AppendLine("SELECT   upper(conversation_id) [Conversation ID], ");
                    sb.AppendLine("         case is_initiator when 1 then 'Yes' else null end [Is initiator?], ");
                    sb.AppendLine("         to_service_name [Name of the service to which this message is sent], ");
                    sb.AppendLine("         to_broker_instance [Identifier of the broker that hosts the service to which this message is sent],");
                    sb.AppendLine("         from_service_name [Name of the service that this message is from], ");
                    sb.AppendLine("         from_broker_instance [Identifier of the broker that hosts the service that this message is from], ");
                    sb.AppendLine("         adjacent_broker_address [Network address to which this message is being sent], ");
                    sb.AppendLine("         message_sequence_number [Sequence number of the message], ");
                    sb.AppendLine("         message_fragment_number [Fragment number that this transport message contains], ");
                    sb.AppendLine("         hops_remaining [Number of times the message may be retransmitted before reaching the final destination], ");
                    sb.AppendLine("         time_to_live [Maximum time for the message to remain active], ");
                    sb.AppendLine("         time_consumed [Time that the message has already been active], ");
                    sb.AppendLine("         Upper(message_id) [ID of the message] ");
                    sb.AppendLine("FROM sys.dm_broker_forwarded_messages ");
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand();
                    da.SelectCommand.CommandText = sb.ToString();
                    da.SelectCommand.CommandTimeout = 0;
                    da.SelectCommand.CommandType = CommandType.Text;
                    da.SelectCommand.Connection = connection;

                    ds = new DataSet();
                    da.Fill(ds);

                    gdvForwarded.DataSource = ds.Tables[0];
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPage active = tcMain.SelectedTab;

            string methodName = active.Name + "_Enter";

            Type t = this.GetType();

            MethodInfo m = t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);

            if (m != null)
                m.Invoke(this, new object[] { active, EventArgs.Empty });
        }

        private void refreshIntervalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Interval dialog = new Interval();
            if (dialog.ShowDialog() == DialogResult.OK)
                if (dialog.TimeInterval > 0)
                {
                    interval = dialog.TimeInterval;
                }
        }

        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem m = (ToolStripMenuItem)sender;

            if (interval == 0)
            {
                m.Checked = false;
                timer.Stop();
            }
            else
            {
                m.Checked = !m.Checked;

                if (m.Checked)
                {
                    timer.Interval = interval;
                    timer.Start();
                }
                else
                {
                    timer.Stop();
                }
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            refreshToolStripMenuItem_Click(sender, e);
        }

        private void createMessageTypeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_message_type dialog = new create_message_type(this);

            //if (dialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Message type was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createContractToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_contract dialog = new create_contract(this);

            //if (dialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Contract was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void tabMessageTypes_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   mt.name [Name], ");
                sb.AppendLine("         dp.name [Principal], ");
                sb.AppendLine("         mt.validation_desc [Validation], ");
                sb.AppendLine("         mt.xml_collection_id,");
                sb.AppendLine("         (select name from sys.xml_schema_collections WHERE xml_collection_id = mt.xml_collection_id) [XML schema collection]");
                sb.AppendLine("FROM sys.service_message_types mt ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on mt.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvMesssageTypes.DataSource = ds.Tables[0];
                dgvMesssageTypes.Columns["xml_collection_id"].Visible = false;

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabContracts_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   c.name [Name], ");
                sb.AppendLine("         dp.name [Principal] ");
                sb.AppendLine("FROM sys.service_contracts c ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on c.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvContracts.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void tabServices_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   s.name [Name], ");
                sb.AppendLine("         dp.name [Principal] ");
                sb.AppendLine("FROM sys.services s ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp on s.principal_id = dp.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvServices.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }


        }

        string messageTypeColumnName;

        private void dgvContracts_MouseClick(object sender, MouseEventArgs e)
        {
        }

        private void dgvContracts_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        }

        private void dgvMesssageTypes_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (messageTypeColumnName == "XML schema collection") cmsXml.Show(Control.MousePosition);
            }
        }

        private void dgvMesssageTypes_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex > 0)
            {
                messageTypeColumnName = dgvMesssageTypes.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;

                if (dgvMesssageTypes.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name == "XML schema collection")
                {
                    schema_principal = dgvMesssageTypes.Rows[e.RowIndex].Cells["principal"].Value;
                    schema_collection = dgvMesssageTypes.Rows[e.RowIndex].Cells["XML schema collection"].Value;

                    if (schema_collection.ToString() != string.Empty) xmlSchema = XmlSchemaCollection(schema_principal, schema_collection);
                }
            }
        }

        private void createQueueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_queue dialog = new create_queue(this);
            //if (dialog.ShowDialog(this) == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Queue was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createServiceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_service dialog = new create_service(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Service was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createRouteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_route dialog = new create_route(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Route was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createCertificateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_certificate dialog = new create_certificate(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Certificate was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createEndpointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_endpoint dialog = new create_endpoint(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Certificate was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void createMasterKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_master_key dialog = new create_master_key();
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Master Key was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void beginConverstionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //begin_converation dialog = new begin_converation(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Conversation was initiated successfully. Check transmissions status.");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void cbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string login = "";
            string auth = "";

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            bool found = false;

            XmlNodeList element = doc.GetElementsByTagName(ServersElement);

            if (element[0] != null)
            {
                if (element[0].ChildNodes.Count > 0)
                {
                    foreach (XmlNode item in element[0].ChildNodes)
                    {
                        foreach (XmlAttribute atr in item.Attributes)
                        {
                            if (atr.Value == cbServer.Text)
                            {
                                found = true;
                            }

                            if (found)
                            {
                                if (atr.Name == "login")
                                {
                                    login = atr.Value;
                                }

                                if (atr.Name == "authentication")
                                {
                                    auth = atr.Value;
                                }
                            }
                        }
                    }
                }
            }

            if (found)
            {
                cbLoginType.SelectedIndex = cbLoginType.Items.IndexOf(auth);
                tbUser.Text = login;
            }
        }

        private void endDialogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //end_conversation dialog = new end_conversation(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Conversation was ended successfully. Check transmissions status.");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void messageTypesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_message_type dialog = new alter_message_type(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Message was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void queuesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_queue dialog = new alter_queue(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Queue was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void servicesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ////alter_service dialog = new alter_service(this);
            ////if (dialog.ShowDialog() == DialogResult.OK)
            ////{
            ////    SqlCommand command = new SqlCommand();
            ////    command.CommandText = dialog.Command;
            ////    command.CommandTimeout = 0;
            ////    command.CommandType = CommandType.Text;
            ////    command.Connection = connection;

            ////    try
            ////    {
            ////        command.ExecuteNonQuery();

            ////        MessageBox.Show("Service was altered successfully");
            ////    }
            ////    catch (Exception exception)
            ////    {
            ////        MessageBox.Show(exception.Message);
            ////    }
            ////}
        }

        private void certificatesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_certificate dialog = new alter_certificate(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Certificate was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void routesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_route dialog = new alter_route(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Route was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void endpointsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_endpoint dialog = new alter_endpoint(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Endpoint was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void codeSigningToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //code_signing dialog = new code_signing(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Code was signed successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void authorizationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //alter_authorization dialog = new alter_authorization(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Authorization was altered successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void conversationToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void loginToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //anonymous_transport_security dialog = new anonymous_transport_security(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Anonymous transport security was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        string guid_column;
        string broker_guid;

        private void dgvBrokers_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (guid_column == "GUID") cmsGuid.Show(Control.MousePosition);
            }
        }

        private void dgvBrokers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.ColumnIndex > 0)
            //{
            //    if (dgvBrokers.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name.ToUpper() == "IS BROKER ENABLED?")
            //    {
            //        bool is_checked = (bool)dgvBrokers.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            //        try
            //        {
            //            Utility.EnableDisableBroker(Database, Connection, !is_checked);
            //            dgvBrokers.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !is_checked;
            //        }
            //        catch (Exception exception)
            //        {
            //            MessageBox.Show(exception.Message);
            //        }
            //    }
            //}
        }

        private void dgvBrokers_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex > 0)
            {
                guid_column = dgvBrokers.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name;

                if (dgvBrokers.Rows[e.RowIndex].Cells[e.ColumnIndex].OwningColumn.Name == "GUID")
                {
                    broker_guid = dgvBrokers.Rows[e.RowIndex].Cells["GUID"].Value.ToString();
                }
            }
        }

        private void copyToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(broker_guid);
        }

        private void remoteServiceBindingToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void targetSodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //anonymous_target_side dialog = new anonymous_target_side(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Anonymous dialog security on target side was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void targetSideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //full_target_side dialog = new full_target_side(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Full dialog security on target side was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void initaitorSideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //full_initiator_side dialog = new full_initiator_side(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Full dialog security on initiator side was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void importingPublicKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //full_inport_from_target dialog = new full_inport_from_target();
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Public key certificate target side was imported successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void importingPublicKeyCertificateOfInitiatorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //full_import_from_initiator dialog = new full_import_from_initiator(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Public key certificate initiator side was imported successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void remoteServiceBindingToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            //remote_service_binding dialog = new remote_service_binding(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Remote service binding was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void initiatorSideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //anonymous_initiator_side dialog = new anonymous_initiator_side(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Anonymous service binding was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void remoteServiceBindingToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //alter_remote_binding dialog = new alter_remote_binding(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Remote service binding was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void tabRemote_Enter(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine("USE [" + current_database + "];");
                sb.AppendLine("SELECT   s.name [Name], ");
                sb.AppendLine("         dp1.name [Principal], ");
                sb.AppendLine("         dp2.name [Remote principal], ");
                sb.AppendLine("         s.remote_service_name [Remote service name] ");
                sb.AppendLine("FROM sys.remote_service_bindings s ");
                sb.AppendLine("LEFT JOIN sys.database_principals dp1 on s.principal_id = dp1.principal_id");
                sb.AppendLine("LEFT JOIN sys.database_principals dp2 on s.remote_principal_id = dp2.principal_id");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;

                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvRemote.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void sendToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void receiveMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //receive dialog = new receive(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("There is no message in the queue");
            //    }
            //    catch (Exception exception)
            //    {
            //        if (exception.Message.Contains(sep))
            //        {
            //            string[] separator = new string[1] { sep };
            //            string[] reply = exception.Message.Split(separator, StringSplitOptions.None);

            //            try
            //            {
            //                string guid = reply[0];
            //                string message_type = reply[1];
            //                string message_body = reply[2];

            //                if (Utility.is_xml_validation(current_database, connection, message_type))
            //                {
            //                    string fileName = tempPath + Path.GetRandomFileName() + ".xml";
            //                    StreamWriter sw = File.CreateText(fileName);
            //                    sw.Write(message_body);
            //                    sw.Close();

            //                    XmlBrowser xb = new XmlBrowser();
            //                    xb.browser.Navigate(fileName);
            //                    xb.Show();
            //                }
            //                else
            //                {
            //                    if (message_body == string.Empty)
            //                    {
            //                        message_body = "<empty>";
            //                    }

            //                    string reply_string = string.Format("Message type: {0}" + Environment.NewLine + "Message body: {1}", message_type, message_body);
            //                    MessageBox.Show(reply_string);
            //                }
            //            }
            //            catch (Exception new_exception)
            //            {
            //                MessageBox.Show(new_exception.Message);
            //            }
            //        }
            //        else
            //        {
            //            MessageBox.Show(exception.Message);
            //        }
            //    }
            //}
        }

        private void dgvServices_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            string service_name = dgvServices.Rows[e.RowIndex].Cells["Name"].Value.ToString();

            try
            {
                StringBuilder sb = new StringBuilder();

                sb.AppendLine(  "select dp1.name Principal, dp.permission_name Permission, dp.state_desc State "+
                                "from sys.services s "+
                                "inner join sys.database_permissions  dp on s.service_id = dp.major_id "+
                                "inner join sys.database_principals dp1 on dp.grantee_principal_id = dp1.principal_id "+
                                "where s.name = @name "+
                                "union all "+
                                "select dp.name Principal, p.permission_name Permission, 'GRANT' State "+
                                "from sys.services s "+
                                "cross apply  sys.fn_builtin_permissions('SERVICE') p "+
                                "inner join sys.database_principals dp on s.principal_id = dp.principal_id "+
                                "where s.name = @name");
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand();
                da.SelectCommand.CommandText = sb.ToString();
                da.SelectCommand.CommandTimeout = 0;
                da.SelectCommand.CommandType = CommandType.Text;
                da.SelectCommand.Connection = connection;
                da.SelectCommand.Parameters.AddWithValue("@name", service_name);
                DataSet ds = new DataSet();
                da.Fill(ds);

                dgvServicePermiss.DataSource = ds.Tables[0];

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }

        }

        private void permissionsToTheServiceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //service_permission dialog = new service_permission(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Permission for service was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void certificatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_certificate dialog = new drop_certificate(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Certificate was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void remoteServiceBindingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_remote_services dialog = new drop_remote_services(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Remote service binding was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void contractsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_contract dialog = new drop_contract(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Contract was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}

        }

        private void endpointsToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //drop_endpoint dialog = new drop_endpoint(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Endpoint was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void messageTypesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_message dialog = new drop_message(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Message type was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}

        }

        private void queuesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_queue dialog = new drop_queue(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Queue was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}

        }

        private void routesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //drop_route dialog = new drop_route(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Route was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}

        }

        private void usersToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //drop_user dialog = new drop_user(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("User was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void servicesToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //drop_service dialog = new drop_service(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Service was dropped successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            scMain.Panel1Collapsed = true;

            tcMain.Visible = true;

            tcMain.TabPages["tabBrokers"].Focus();

            ShowTabs();

            if (dgvBrokers.Rows.Count > 0)
            {
                current_database = dgvBrokers.Rows[0].Cells[0].Value.ToString();
                current_service_broker_guid = dgvBrokers.Rows[0].Cells[1].Value.ToString();

                showMenu();

                this.Text = AppName + " [" + current_database + "]";
            }

        }

        private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
        {
            Cursor.Current = Cursors.Default;
        }

        private void splitContainer1_SplitterMoving(object sender, SplitterCancelEventArgs e)
        {
            if (splitContainer1.Orientation == Orientation.Vertical)
                Cursor.Current = Cursors.NoMoveVert;
            else
                Cursor.Current = Cursors.NoMoveHoriz;   
        }

        private void eventNotificationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //create_event_notification dialog = new create_event_notification(this);
            //if (dialog.ShowDialog() == DialogResult.OK)
            //{
            //    SqlCommand command = new SqlCommand();
            //    command.CommandText = dialog.Command;
            //    command.CommandTimeout = 0;
            //    command.CommandType = CommandType.Text;
            //    command.Connection = connection;

            //    try
            //    {
            //        command.ExecuteNonQuery();

            //        MessageBox.Show("Event notification was created successfully");
            //    }
            //    catch (Exception exception)
            //    {
            //        MessageBox.Show(exception.Message);
            //    }
            //}
        }

        private void mainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
        }
 
    }
}